<template>
	<h1>这是COne组件</h1>
	<h4>num:{{num}}</h4>
	<h3>id:{{id}}</h3>
	<input type="text" v-model="uname">
	<input type="text" v-model="id">
	<button @click="stop">停用侦听器</button>
</template>

<script>
	import {ref,reactive,toRefs,watch} from 'vue'
	export default{
		setup(props,context){//composition API的入口
			const num = ref(0)
			const str = ref("测试")
			const state = reactive({
				id:101,
				uname:'莫愁'
			})
			
			//只要num有变化 会触发watch的回调 watch会在创建时自动调用
			// watch(()=>{console.log(num.value)})
			
			/* val:新的值 oval:旧的值 */
			watch(num,(val,oval)=>{
				console.log(val,oval)
				console.log("c num:",num.value)
			},{//第二个参数obj immediate deep
				immediate:false //默认就是只有数据改变时才会监听,第一次不会执行,设置true第一次也会执行
			})
			
			//侦听state下的id,数据的变化
			watch(state,(val,oval)=>{
				console.log("id:",val.id,oval)
			},{
				immediate:true ,
				deep:true,//开启深度侦听 能够侦听到对象的属性值的变化
			})
			
			//单个侦听state下的uname
			watch(()=>state.uname,(uname,p)=>{
				console.log(uname,p)
			},{
				immediate:true ,
			})
			//const s = toRefs(state)  watch(s.id,()=>{})  等于 ()=>state.id
			
			//多个侦听数据
			const stop = watch([()=>state.id,()=>state.uname],([id,uname],[oid,oname])=>{
				console.log("id:",id,oid)
				console.log("uname",uname,oname)
			})			
			return{
				num,stop,
				...toRefs(state)
			}
		}
	}
</script>

<style scoped>
a {
  color: #42b983;
}
button{
	margin-left: 10px;
}
</style>